package db

import (
	"log"
	"poker/env"
	"time"

	redis "github.com/go-redis/redis/v7"
	"github.com/nlh1996/utils"
)

var (
	client   *redis.Client
	redisEnv = env.GlobalData.Server
)

// InitRedis .
func InitRedis() {
	client = redis.NewClient(&redis.Options{
		Addr:     redisEnv.RedisAddress + ":" + utils.IntToString(redisEnv.RedisPort),
		Password: redisEnv.RedisPassword,
		DB:       0,
		PoolSize: 10,
	})

	// 通过 cient.Ping() 来检查是否成功连接到了 redis 服务器
	_, err := client.Ping().Result()
	if err != nil {
		log.Panicln(err)
	}
	log.Println("Connected to Redis!")
	return
}

// GetRedisClient .
func GetRedisClient() *redis.Client {
	return client
}

func printErr(funcName string, err error) {
	log.Println(err, "in", funcName)
}

// Set .
func Set(key string, value interface{}, dt time.Duration) {
	if err := client.Set(key, value, dt).Err(); err != nil {
		printErr("Set", err)
	}
}

// Get .
func Get(key string) string {
	val, err := client.Get(key).Result()
	if err != nil {
		printErr("Get", err)
	}
	return val
}

// GetInt .
func GetInt(key string) int {
	val, err := client.Get(key).Int64()
	if err != nil {
		printErr("MGet", err)
	}
	return int(val)
}

// GetFloat .
func GetFloat(key string) float64 {
	val, err := client.Get(key).Float64()
	if err != nil {
		printErr("GetFloat", err)
	}
	return val
}

// MSet .
func MSet(s ...interface{}) {
	if err := client.MSet(s...).Err(); err != nil {
		printErr("MSet", err)
	}
}

// MGet .
func MGet(keys ...string) []interface{} {
	vals, err := client.MGet(keys...).Result()
	if err != nil {
		printErr("MGet", err)
	}
	return vals
}

// HMSet .
func HMSet(name string, fields map[string]string) {
	client.HMSet(name, fields)
}

// LPush .
func LPush(key string, values ...interface{}) {
	if err := client.LPush(key, values...).Err(); err != nil {
		printErr("LPush", err)
	}
	return
}

// BLPop .
func BLPop(timeout time.Duration, keys ...string) []string {
	res, err := client.BLPop(timeout, keys...).Result()
	if err != nil {
		printErr("BLPop", err)
	}
	return res
}

// RPush .
func RPush(key string, values ...interface{}) {
	if err := client.RPush(key, values...).Err(); err != nil {
		printErr("RPush", err)
	}
	return
}

// BRPop .
func BRPop(timeout time.Duration, keys ...string) []string {
	res, err := client.BRPop(timeout, keys...).Result()
	if err != nil {
		printErr("BRPop", err)
	}
	return res
}
